package top.scsoul.pas.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.scsoul.pas.entity.Clazz;
import top.scsoul.pas.entity.Role;
import top.scsoul.pas.entity.User;
import top.scsoul.pas.repository.ClazzRepository;
import top.scsoul.pas.repository.UserRepository;
import top.scsoul.pas.service.UserService;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
@Transactional(rollbackOn = Exception.class)
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    ClazzRepository classRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public User login(String loginName) {
        User user = userRepository.findByLoginName(loginName);
        if (user != null) {
            user.setLastLoginTime(new Date());
            userRepository.save(user);
        }
        return user;
    }

    @Override
    public List<User> getTeachers() {
        return userRepository.getTachers();
    }

    @Override
    public Page<User> listTeachers(int currentPage, int pageSize) {
        PageRequest pageRequest = PageRequest.of(currentPage - 1, pageSize);
        return userRepository.findAll(pageRequest);
    }

    @Override
    public boolean existsUserByLoginName(String loginName) {
        long countByLoginName = userRepository.getCountByLoginName(loginName);
        return countByLoginName > 0;
    }

    @Override
    public void saveUser(User user) {
        user.setLastLoginTime(new Date());
        user.setCreated(new Date());
        user.setState(1);
        user.setPassword(passwordEncoder.encode("123456"));
        userRepository.save(user);
    }

    @Override
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public void changeState(Long id, String state) {
        if (isAdmin(id)) {
            throw new RuntimeException("不能修改管理员的状态！");
        }
        userRepository.changeState(id, state);
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.getById(id);
    }

    @Override
    public void updateUser(User user) {

        userRepository.save(user);
    }

    @Override
    public boolean isAdmin(Long id) {
        User user = userRepository.getById(id);
        List<Role> roles = user.getRoles();
        for (Role role : roles) {
            if ("ROLE_ADMIN".equals(role.getName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<Clazz> getSelfClazz(Long id) {
        return classRepository.getAllClazzByLeaderId(id);
    }
}
